{% extends "base.html" %}

{% block title %}管理员面板{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- 统计卡片 -->
        <div class="col-12 mb-4">
            <div class="row" id="statsRow">
                <div class="col-md-3 mb-3">
                    <div class="stats-card">
                        <div class="d-flex align-items-center position-relative">
                            <div class="bg-white bg-opacity-20 rounded-circle p-3 me-3">
                                <i class="bi bi-images fs-1 text-white"></i>
                            </div>
                            <div>
                                <h2 class="mb-0" id="totalImages">-</h2>
                                <p class="mb-0 opacity-90">总图片数</p>
                                <small class="opacity-75">
                                    <i class="bi bi-graph-up me-1"></i>图片管理
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card" style="background: linear-gradient(135deg, #059669 0%, #10b981 100%);">
                        <div class="d-flex align-items-center position-relative">
                            <div class="bg-white bg-opacity-20 rounded-circle p-3 me-3">
                                <i class="bi bi-hdd fs-1 text-white"></i>
                            </div>
                            <div>
                                <h2 class="mb-0" id="totalSize">-</h2>
                                <p class="mb-0 opacity-90">存储大小</p>
                                <small class="opacity-75">
                                    <i class="bi bi-database me-1"></i>空间使用
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card" style="background: linear-gradient(135deg, #d97706 0%, #f59e0b 100%);">
                        <div class="d-flex align-items-center position-relative">
                            <div class="bg-white bg-opacity-20 rounded-circle p-3 me-3">
                                <i class="bi bi-calendar-day fs-1 text-white"></i>
                            </div>
                            <div>
                                <h2 class="mb-0" id="todayUploads">-</h2>
                                <p class="mb-0 opacity-90">今日上传</p>
                                <small class="opacity-75">
                                    <i class="bi bi-clock me-1"></i>实时统计
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card" style="background: linear-gradient(135deg, #7c3aed 0%, #8b5cf6 100%);">
                        <div class="d-flex align-items-center position-relative">
                            <div class="bg-white bg-opacity-20 rounded-circle p-3 me-3">
                                <i class="bi bi-person-check fs-1 text-white"></i>
                            </div>
                            <div>
                                <h2 class="mb-0">{{ current_user.username }}</h2>
                                <p class="mb-0 opacity-90">当前管理员</p>
                                <small class="opacity-75">
                                    <i class="bi bi-shield-check me-1"></i>超级权限
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 上传区域 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex align-items-center">
                        <div class="bg-primary bg-opacity-10 rounded-circle p-2 me-3">
                            <i class="bi bi-cloud-upload text-primary"></i>
                        </div>
                        <h5 class="mb-0">图片上传</h5>
                    </div>
                </div>
                <div class="card-body">
                    <div class="upload-area" id="uploadArea">
                        <div class="float-animation">
                            <i class="bi bi-cloud-upload" style="font-size: 4rem; color: #6b7280;"></i>
                        </div>
                        <h4 class="mt-3 mb-2 fw-bold">拖拽文件到此处或点击选择</h4>
                        <p class="text-muted mb-3">支持 PNG, JPG, JPEG, GIF, BMP, WEBP 格式，最大 16MB</p>
                        <input type="file" id="fileInput" class="d-none" multiple accept="image/*">
                        <button type="button" class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                            <i class="bi bi-folder2-open me-2"></i>选择文件
                        </button>
                        <div class="mt-3">
                            <small class="text-muted">
                                <i class="bi bi-info-circle me-1"></i>
                                支持批量上传，自动生成缩略图
                            </small>
                        </div>
                    </div>
                    
                    <!-- 上传进度 -->
                    <div id="uploadProgress" class="mt-4 d-none">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-semibold">
                                <i class="bi bi-upload me-2"></i>正在上传<span class="loading-dots"></span>
                            </span>
                            <span id="uploadPercent" class="badge bg-primary">0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" style="width: 0%"></div>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted" id="uploadStatus">准备上传...</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图片管理 -->
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <div class="bg-primary bg-opacity-10 rounded-circle p-2 me-3">
                            <i class="bi bi-images text-primary"></i>
                        </div>
                        <h5 class="mb-0">图片管理</h5>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-primary btn-sm" onclick="refreshImages()">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新
                        </button>
                        <button class="btn btn-outline-danger btn-sm" onclick="deleteSelected()" id="deleteSelectedBtn" disabled>
                            <i class="bi bi-trash me-1"></i>删除选中
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 搜索和筛选 -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="searchInput" placeholder="搜索图片名称...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="sortSelect">
                                <option value="time_desc">按时间降序</option>
                                <option value="time_asc">按时间升序</option>
                                <option value="name_asc">按名称升序</option>
                                <option value="size_desc">按大小降序</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAll">
                                <label class="form-check-label" for="selectAll">
                                    全选
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- 图片网格 -->
                    <div id="loadingSpinner" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">加载图片中...</p>
                    </div>

                    <div id="imagesGrid" class="row g-3" style="display: none;">
                        <!-- 图片卡片将在这里动态生成 -->
                    </div>

                    <div id="noImages" class="text-center py-5" style="display: none;">
                        <i class="bi bi-images" style="font-size: 4rem; color: #6b7280;"></i>
                        <h4 class="mt-3 text-muted">暂无图片</h4>
                        <p class="text-muted">开始上传您的第一张图片吧！</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 图片详情模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-8">
                        <img id="modalImage" class="img-fluid rounded" style="max-height: 400px;">
                    </div>
                    <div class="col-md-4">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>文件名:</strong></td>
                                <td id="modalFilename">-</td>
                            </tr>
                            <tr>
                                <td><strong>原始名称:</strong></td>
                                <td id="modalOriginalName">-</td>
                            </tr>
                            <tr>
                                <td><strong>大小:</strong></td>
                                <td id="modalSize">-</td>
                            </tr>
                            <tr>
                                <td><strong>尺寸:</strong></td>
                                <td id="modalDimensions">-</td>
                            </tr>
                            <tr>
                                <td><strong>上传时间:</strong></td>
                                <td id="modalUploadTime">-</td>
                            </tr>
                            <tr>
                                <td><strong>上传者:</strong></td>
                                <td id="modalUploader">-</td>
                            </tr>
                        </table>
                        <div class="mt-3">
                            <input type="text" class="form-control" id="imageUrl" readonly>
                            <button class="btn btn-outline-primary btn-sm mt-2" onclick="copyUrl()">
                                <i class="bi bi-clipboard"></i> 复制链接
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="deleteImage()">
                    <i class="bi bi-trash"></i> 删除
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentImages = [];
let selectedImages = new Set();
let currentImageId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadStats();
    loadImages();
    initializeUpload();
    initializeSearch();
});

// 加载统计信息
async function loadStats() {
    try {
        const response = await fetch('/api/stats');
        const stats = await response.json();
        
        document.getElementById('totalImages').textContent = stats.total_images;
        document.getElementById('totalSize').textContent = stats.total_size_mb + ' MB';
        document.getElementById('todayUploads').textContent = stats.today_uploads;
    } catch (error) {
        console.error('Failed to load stats:', error);
    }
}

// 加载图片列表
async function loadImages() {
    const loadingSpinner = document.getElementById('loadingSpinner');
    const imagesGrid = document.getElementById('imagesGrid');
    const noImages = document.getElementById('noImages');
    
    loadingSpinner.style.display = 'block';
    imagesGrid.style.display = 'none';
    noImages.style.display = 'none';
    
    try {
        const response = await fetch('/api/images');
        const images = await response.json();
        
        currentImages = images;
        selectedImages.clear();
        updateDeleteButton();
        
        if (images.length === 0) {
            loadingSpinner.style.display = 'none';
            noImages.style.display = 'block';
        } else {
            renderImages(images);
            loadingSpinner.style.display = 'none';
            imagesGrid.style.display = 'flex';
        }
    } catch (error) {
        console.error('Failed to load images:', error);
        showToast('加载图片失败', 'error');
        loadingSpinner.style.display = 'none';
    }
}

// 渲染图片网格
function renderImages(images) {
    const grid = document.getElementById('imagesGrid');
    grid.innerHTML = '';
    
    images.forEach(image => {
        const col = document.createElement('div');
        col.className = 'col-md-3 col-sm-4 col-6';
        
        col.innerHTML = `
            <div class="image-card">
                <div class="position-relative overflow-hidden">
                    <img src="/thumbnails/${image.thumbnail}" 
                         class="image-thumbnail" 
                         alt="${image.original_name}"
                         style="cursor: pointer;"
                         onclick="showImageModal('${image.id}')">
                    <div class="position-absolute top-0 start-0 m-2">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" 
                                   onchange="toggleImageSelection('${image.id}')"
                                   ${selectedImages.has(image.id) ? 'checked' : ''}>
                        </div>
                    </div>
                    <div class="position-absolute top-0 end-0 m-2">
                        <div class="btn-group-vertical" role="group">
                            <button class="btn btn-light btn-sm opacity-75" onclick="showImageModal('${image.id}')" title="查看详情">
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="btn btn-danger btn-sm opacity-75" onclick="deleteImageById('${image.id}')" title="删除图片">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="position-absolute bottom-0 start-0 end-0 bg-gradient-to-t from-black to-transparent p-3">
                        <div class="text-white">
                            <small class="fw-semibold d-block">${formatFileSize(image.size)}</small>
                            <small class="opacity-75">${image.width} × ${image.height}</small>
                        </div>
                    </div>
                </div>
                <div class="p-3">
                    <h6 class="mb-2 text-truncate fw-semibold" title="${image.original_name}">${image.original_name}</h6>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <small class="text-muted">
                            <i class="bi bi-calendar3 me-1"></i>${formatDate(image.upload_time)}
                        </small>
                        <span class="badge bg-secondary">${image.uploader}</span>
                    </div>
                    <div class="d-flex gap-1">
                        <button class="btn btn-outline-primary btn-sm flex-fill" onclick="showImageModal('${image.id}')">
                            <i class="bi bi-eye me-1"></i>详情
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" onclick="copyImageUrl('${image.filename}')" title="复制链接">
                            <i class="bi bi-clipboard"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        grid.appendChild(col);
    });
}

// 显示图片详情模态框
function showImageModal(imageId) {
    const image = currentImages.find(img => img.id === imageId);
    if (!image) return;
    
    currentImageId = imageId;
    
    document.getElementById('modalImage').src = `/uploads/${image.filename}`;
    document.getElementById('modalFilename').textContent = image.filename;
    document.getElementById('modalOriginalName').textContent = image.original_name;
    document.getElementById('modalSize').textContent = formatFileSize(image.size);
    document.getElementById('modalDimensions').textContent = `${image.width} × ${image.height}`;
    document.getElementById('modalUploadTime').textContent = formatDate(image.upload_time);
    document.getElementById('modalUploader').textContent = image.uploader;
    document.getElementById('imageUrl').value = `${window.location.origin}/uploads/${image.filename}`;
    
    new bootstrap.Modal(document.getElementById('imageModal')).show();
}

// 复制图片链接
function copyImageUrl(filename) {
    const url = `${window.location.origin}/uploads/${filename}`;
    navigator.clipboard.writeText(url).then(() => {
        showToast('图片链接已复制到剪贴板', 'success');
    }).catch(() => {
        // 备用方案
        const textArea = document.createElement('textarea');
        textArea.value = url;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showToast('图片链接已复制到剪贴板', 'success');
    });
}

// 复制图片链接
function copyUrl() {
    const urlInput = document.getElementById('imageUrl');
    urlInput.select();
    navigator.clipboard.writeText(urlInput.value).then(() => {
        showToast('链接已复制到剪贴板', 'success');
    });
}

// 删除图片
async function deleteImage() {
    if (!currentImageId) return;
    
    if (!confirm('确定要删除这张图片吗？')) return;
    
    try {
        const response = await fetch(`/api/images/${currentImageId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showToast('删除成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('imageModal')).hide();
            loadImages();
            loadStats();
        } else {
            showToast(result.error || '删除失败', 'error');
        }
    } catch (error) {
        console.error('Delete failed:', error);
        showToast('删除失败', 'error');
    }
}

// 通过ID删除图片
async function deleteImageById(imageId) {
    if (!confirm('确定要删除这张图片吗？')) return;
    
    try {
        const response = await fetch(`/api/images/${imageId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showToast('删除成功', 'success');
            loadImages();
            loadStats();
        } else {
            showToast(result.error || '删除失败', 'error');
        }
    } catch (error) {
        console.error('Delete failed:', error);
        showToast('删除失败', 'error');
    }
}

// 切换图片选择状态
function toggleImageSelection(imageId) {
    if (selectedImages.has(imageId)) {
        selectedImages.delete(imageId);
    } else {
        selectedImages.add(imageId);
    }
    updateDeleteButton();
    updateSelectAllCheckbox();
}

// 更新删除按钮状态
function updateDeleteButton() {
    const btn = document.getElementById('deleteSelectedBtn');
    btn.disabled = selectedImages.size === 0;
    btn.innerHTML = selectedImages.size > 0 
        ? `<i class="bi bi-trash"></i> 删除选中 (${selectedImages.size})`
        : '<i class="bi bi-trash"></i> 删除选中';
}

// 更新全选复选框状态
function updateSelectAllCheckbox() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const totalImages = currentImages.length;
    const selectedCount = selectedImages.size;
    
    if (selectedCount === 0) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = false;
    } else if (selectedCount === totalImages) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = true;
    } else {
        selectAllCheckbox.indeterminate = true;
    }
}

// 全选/取消全选
document.getElementById('selectAll').addEventListener('change', function() {
    if (this.checked) {
        currentImages.forEach(image => selectedImages.add(image.id));
    } else {
        selectedImages.clear();
    }
    updateDeleteButton();
    renderImages(currentImages);
});

// 删除选中的图片
async function deleteSelected() {
    if (selectedImages.size === 0) return;
    
    if (!confirm(`确定要删除选中的 ${selectedImages.size} 张图片吗？`)) return;
    
    const deletePromises = Array.from(selectedImages).map(imageId => 
        fetch(`/api/images/${imageId}`, { method: 'DELETE' })
    );
    
    try {
        await Promise.all(deletePromises);
        showToast(`成功删除 ${selectedImages.size} 张图片`, 'success');
        selectedImages.clear();
        loadImages();
        loadStats();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showToast('批量删除失败', 'error');
    }
}

// 刷新图片列表
function refreshImages() {
    loadImages();
    loadStats();
}

// 初始化上传功能
function initializeUpload() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    
    // 拖拽上传
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        handleFiles(files);
    });
    
    // 点击上传
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });
    
    fileInput.addEventListener('change', function() {
        handleFiles(this.files);
    });
}

// 处理文件上传
async function handleFiles(files) {
    if (files.length === 0) return;
    
    const uploadProgress = document.getElementById('uploadProgress');
    const progressBar = document.getElementById('progressBar');
    const uploadPercent = document.getElementById('uploadPercent');
    const uploadStatus = document.getElementById('uploadStatus');
    
    uploadProgress.classList.remove('d-none');
    uploadStatus.textContent = `准备上传 ${files.length} 个文件...`;
    
    let uploaded = 0;
    const total = files.length;
    let failed = 0;
    
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        uploadStatus.textContent = `正在上传: ${file.name} (${i + 1}/${total})`;
        
        try {
            await uploadFile(file);
            uploaded++;
            
            const percent = Math.round(((uploaded + failed) / total) * 100);
            progressBar.style.width = percent + '%';
            uploadPercent.textContent = percent + '%';
            
            uploadStatus.textContent = `已完成: ${uploaded}/${total}`;
            
        } catch (error) {
            console.error('Upload failed:', error);
            failed++;
            showToast(`文件 ${file.name} 上传失败`, 'error');
            
            const percent = Math.round(((uploaded + failed) / total) * 100);
            progressBar.style.width = percent + '%';
            uploadPercent.textContent = percent + '%';
        }
    }
    
    // 上传完成
    uploadStatus.textContent = `上传完成! 成功: ${uploaded}, 失败: ${failed}`;
    
    setTimeout(() => {
        uploadProgress.classList.add('d-none');
        progressBar.style.width = '0%';
        uploadPercent.textContent = '0%';
        uploadStatus.textContent = '准备上传...';
    }, 2000);
    
    if (uploaded > 0) {
        showToast(`成功上传 ${uploaded} 张图片`, 'success');
        loadImages();
        loadStats();
    }
    
    // 清空文件输入
    document.getElementById('fileInput').value = '';
}

// 上传单个文件
async function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
    });
    
    if (!response.ok) {
        throw new Error('Upload failed');
    }
    
    return response.json();
}

// 初始化搜索和排序
function initializeSearch() {
    const searchInput = document.getElementById('searchInput');
    const sortSelect = document.getElementById('sortSelect');
    
    searchInput.addEventListener('input', filterAndSortImages);
    sortSelect.addEventListener('change', filterAndSortImages);
}

// 过滤和排序图片
function filterAndSortImages() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const sortType = document.getElementById('sortSelect').value;
    
    let filteredImages = currentImages.filter(image => 
        image.original_name.toLowerCase().includes(searchTerm) ||
        image.filename.toLowerCase().includes(searchTerm)
    );
    
    // 排序
    switch (sortType) {
        case 'time_asc':
            filteredImages.sort((a, b) => new Date(a.upload_time) - new Date(b.upload_time));
            break;
        case 'time_desc':
            filteredImages.sort((a, b) => new Date(b.upload_time) - new Date(a.upload_time));
            break;
        case 'name_asc':
            filteredImages.sort((a, b) => a.original_name.localeCompare(b.original_name));
            break;
        case 'size_desc':
            filteredImages.sort((a, b) => b.size - a.size);
            break;
    }
    
    renderImages(filteredImages);
}
</script>
{% endblock %}
